#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <arpa/inet.h>

#include "global.h"
#include "logger.h"
#include "threadpool.h"
#include "readconf.h"
#include "funcutil.h"

static void cleanup(); //释放资源专用函数

CSocket     g_socket;
CThreadPool g_threadpool;
pid_t   pid;
pid_t   ppid;
bool    isMaster;
int     g_stop;

sig_atomic_t reap; //子进程用来标记信号量状态的原子变量

int main(int argc, const char** argv) {
    int exitcode = 0;
    g_stop = 0;
    pid = getpid();
    ppid = getppid();

    CConfig::instance()->init();
    cfg_t cfg = CConfig::instance()->get();

    wb::Logger::logger_init();

    int daemonret = wb::daemon();
    if (daemonret == -1)
    {
        cleanup();
        exitcode = 1;
        goto flagexit;
    }
    if (daemonret == 1) //父进程创建后台成功，释放资源并退出
    {
        cleanup();
        exitcode = 0;
        return exitcode;
    }
    //开始主(子进程)进程循环
    wb::master_cycle();

flagexit: //不管什么原因走到这，都得释放资源
    wb::Logger::logger_stderr(0, "exit!!! Bye...");
    cleanup();
    return exitcode;
}

void cleanup()
{
    wb::Logger::close();
}